package services

import (
	"context"
	"fmt"
	"github.com/sirupsen/logrus"
	"regexp"
	"strings"
	"wecom_rebot/common"
	"wecom_rebot/core"
	"wecom_rebot/models"
)

var xhsBindSaleLogger *logrus.Logger

// InitXhsBindSaleLogger 移除 init() 函数，改为显式初始化函数
func InitXhsBindSaleLogger() {
	// 确保在 common 初始化后调用
	xhsBindSaleLogger = core.InitLogger(common.LogsErrorMap[27])
}

type XhsBindAccountAnalyzeContent struct {
	UserEmail string
	XhsEmail  string
}

type BindSaleService struct{}

func (s *BindSaleService) Handle(msgId int, subjectName, roomId string, content []string, jobId uint64) error {
	var msg = &models.Msg{}

	fmt.Println("xhsBindSaleLogger", "原始结构Id：", msgId)
	// 获取数据
	err := common.DB.Where("id = ?", msgId).First(&msg).Error
	if err != nil {
		xhsBindSaleLogger.Error("小红书获取数据失败", common.LogsErrorMap[common.MysqlError], msgId, err)
		return err
	}

	xhsBindSaleLogger.Info("xhsBindSaleLogger", "原始结构：", content)

	// 处理需要的数据结构
	result, err := s.analyzeContent(content)
	if err != nil {
		xhsBindSaleLogger.Error(err)
		return err
	}

	xhsBindSaleLogger.Info("xhsBindSaleLogger", result)

	// 移除功能行
	msg.Content = RemoveTitle(msg)
	fmt.Println("移除后的结构：", msg, "广告主信息：", content)

	rdb := core.InitRedis(13)
	ctx := context.Background()

	cookies, _ := rdb.Get(ctx, "laravel_database_xhs_adv_cookies").Result()

	xhsBindSaleLogger.Info("xhsBindSaleLogger", "cookies:", cookies)
	return nil
}

// analyzeContent 解析内容为广告主信息数组
func (s *BindSaleService) analyzeContent(content []string) (*[]XhsBindAccountAnalyzeContent, error) {
	// 初始化结果变量
	var userEmail []string
	var mediaEmail []string

	// 编译正则表达式（支持中文逗号、顿号）
	sepRegex, err := regexp.Compile(`[,，、]`)
	if err != nil {
		copyAccountTxLogger.Error("邮箱分隔符正则表达式编译失败", err)
		return nil, fmt.Errorf("正则表达式编译失败: %w", err)
	}

	// 遍历内容行
	for _, line := range content {
		// 小红书绑定用户邮箱
		if strings.HasPrefix(line, "小红书绑定用户邮箱:") {
			raw := strings.TrimPrefix(line, "小红书绑定用户邮箱:")
			emails := sepRegex.Split(raw, -1)
			for _, email := range emails {
				trimmedEmail := strings.TrimSpace(email)
				if trimmedEmail != "" {
					userEmail = append(userEmail, trimmedEmail)
				}
			}
		}
		// 媒体账户邮箱
		if strings.HasPrefix(line, "媒体账户邮箱:") {
			raw := strings.TrimPrefix(line, "媒体账户邮箱:")
			emails := sepRegex.Split(raw, -1)
			for _, email := range emails {
				trimmedEmail := strings.TrimSpace(email)
				if trimmedEmail != "" {
					mediaEmail = append(mediaEmail, trimmedEmail)
				}
			}
		}
	}
	var result []XhsBindAccountAnalyzeContent

	for _, uEmial := range userEmail {
		for _, mEmail := range mediaEmail {
			result = append(result, XhsBindAccountAnalyzeContent{
				UserEmail: uEmial,
				XhsEmail:  mEmail,
			})
		}
	}

	return &result, nil
}
